from django.db import models

# Create your models here.

from django.contrib.auth.hashers import make_password

from django.contrib.auth.hashers import make_password,check_password



# 自定义加密规则
# class CustomPasswordHasher:
#     def make_password(self, password):
#         # 自定义加密逻辑，例如使用PBKDF2算法
#         import hashlib
#         return hashlib.pbkdf2_hmac('sha256', password.encode(), b'salt', 100000)
#
#     def check_password(self, password, encoded_password):
#         # 自定义验证逻辑
#         return self.make_password(password) == encoded_password






#登录注册使用
class UserModel(models.Model):
    username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=128,verbose_name="密码")  # 存储加密后的密码
    email = models.EmailField(unique=True, verbose_name='邮箱')
    avatar = models.ImageField(upload_to='avatar/', default='avatar/touxiang.jpg', verbose_name='头像')
    mobile = models.CharField(max_length=11, null=True, blank=True, verbose_name='手机号')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    def save(self, *args, **kwargs):
        if not self.id:  # 如果是新创建的用户，加密密码
            self.password = make_password(self.password)
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.id}"+f"{self.username}"
    class Meta:
        db_table = 'user'
        verbose_name = '登录注册表'
        verbose_name_plural = verbose_name






# 角色表
#新增实现角色继承
class Role(models.Model):
    name = models.CharField(max_length=100,verbose_name="角色名称")
    #自关联继承基础角色
    pid = models.ForeignKey('self', on_delete=models.CASCADE,verbose_name="父级角色",null=True,blank=True,related_name="rolepid",default='')
    #标识是否是基础角色
    isbase = models.SmallIntegerField(choices= ((0,'正常'), (1,'基础')),default=0,verbose_name="是否为基础角色")
    def __str__(self):
        return f"{self.id}-"+f"{self.name}-"+f"{self.pid}"+f"{self.get_isbase_display()}-"
    class Meta:
        db_table = 'role'
        verbose_name = '角色表'
        verbose_name_plural = verbose_name


class Workflow(models.Model):
   name=models.CharField(max_length=20,verbose_name="工作流名称",unique=True)
   params=models.TextField(verbose_name="工作流参数")
   status=models.IntegerField(choices= ((0,'可用'), (1,'停用')),verbose_name="工作流状态")
   def __str__(self):
       return self.name
   class Meta:
       db_table = 'workflow'
       verbose_name = '工作流表'
class WorkflowPermission(models.Model):
    roleid=models.ForeignKey(Role, on_delete=models.CASCADE,verbose_name="角色ID",related_name='role_workflow')
    workflowid=models.ForeignKey(Workflow, on_delete=models.CASCADE,verbose_name="工作流ID")
    def __str__(self):
        return f"{self.roleid.name}-{self.workflowid.name}"

    class Meta:
        db_table = 'workflowpermission'
        verbose_name = '工作流权限表'

# 用户角色表
class UserRole(models.Model):
    userid = models.ForeignKey(UserModel, on_delete=models.CASCADE,verbose_name="用户ID",null= True )
    roleid = models.ForeignKey(Role, on_delete=models.CASCADE,verbose_name="角色ID")
    def __str__(self):
        return f"{self.id}-"+f"{self.userid.username}-"+f"{self.roleid.name}"
    class Meta:
        db_table = 'user_role'
        verbose_name = '用户角色表'
        verbose_name_plural = verbose_name

# 资源表
class Resource(models.Model):
    name = models.CharField(max_length=100,verbose_name="资源名称")
    url = models.CharField(max_length=200,verbose_name="资源路径",default="",blank=True,null=True)
    #自关联
    pname = models.ForeignKey('self', on_delete=models.CASCADE,verbose_name="父级资源",null=True,blank=True,related_name='children',default='')
    #自关联子资源
    sname = models.ForeignKey('self', on_delete=models.CASCADE,verbose_name="子资源",blank=True,null=True,related_name='siblings',default='')

    def __str__(self):
        return f"{self.id}-"+f"{self.url}-"+f"{self.name}-"
    class Meta:
        db_table = 'resource'
        verbose_name = '资源表'
        verbose_name_plural = verbose_name

# 角色资源表
class RoleResource(models.Model):
    roleid = models.ForeignKey(Role, on_delete=models.CASCADE,verbose_name="角色ID",related_name='roles')
    resourceid = models.ForeignKey(Resource, on_delete=models.CASCADE,verbose_name="资源ID",)
    def __str__(self):
        return f"{self.id}-"+f"{self.roleid.name}  - {self.resourceid.name}"
    class Meta:
        db_table = 'role_resource'
        verbose_name = '角色资源表'
        verbose_name_plural = verbose_name


# 人员管理
class personRole(models.Model):
    TYPE_CHOICES = [
        ('1', '管理员'),
        ('2', '上门人员'),
    ]
    STATE_CHOICES = [
        ('1', '启用'),
        ('2', '禁用'),
    ]
    name = models.CharField(max_length=20, verbose_name="姓名")
    mobile = models.CharField(max_length=11, verbose_name="手机号")
    type = models.CharField(max_length=1,choices=TYPE_CHOICES,verbose_name="人员类型",default='2')
    state = models.CharField(max_length=1,choices=STATE_CHOICES,verbose_name="人员状态",default='1')
    class Meta:
        db_table = 'person_role'
        verbose_name = '人员管理'

# 资源权限表
class ResourceInterface(models.Model):
    resid = models.ForeignKey(Resource, on_delete=models.SET_NULL, null=True, related_name='interface')
    url = models.CharField(max_length=100)

    class Meta:
        verbose_name = '接口权限表'
        verbose_name_plural = '接口权限表'
        db_table = "resource_interface"
    def __str__(self):
        return f"{self.id}-"+f"{self.resid.name}-"+f"{self.url}"


# 保证金管理
class deposit(models.Model):
    name = models.CharField(max_length=20, verbose_name="姓名")
    price = models.IntegerField()
    class Meta:
        db_table = 'deposit'
        verbose_name = '保证金管理'


# 隐私协议
class privacy(models.Model):
    content = models.TextField(verbose_name="内容")
    class Meta:
        db_table = 'privacy'
        verbose_name = '隐私协议'



# 订单
class ServiceOrder(models.Model):
    name = models.CharField(max_length=255, verbose_name="服务名称")
    img = models.ImageField(upload_to='service_images/', verbose_name="服务图片", null=True, blank=True)
    order_number = models.CharField(max_length=50, unique=True, verbose_name="订单编号")
    dispatch_time = models.DateTimeField(verbose_name="派单时间")
    service_address = models.CharField(max_length=255, verbose_name="服务地址")
    contact_person = models.CharField(max_length=100, verbose_name="联系人")
    appointment_time = models.DateTimeField(verbose_name="预约时间")
    customer_notes = models.TextField(verbose_name="客户备注", null=True, blank=True)
    price = models.IntegerField(verbose_name="价格")
    quantity = models.PositiveIntegerField(verbose_name="数量")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "服务订单"
        verbose_name_plural = "服务订单"


# 提现
class WithModel(models.Model):
    name = models.CharField(max_length=20,verbose_name='真实姓名')
    money= models.IntegerField(verbose_name='提现金额')
    account=models.CharField(max_length=20,verbose_name='账号')
    class Meta:
        db_table = 'withdraw'
        verbose_name = '提现表'
    def __str__(self):
        return self.name

# 服务
class Service(models.Model):
    SERVICE_TYPE_CHOICES ={
        (0,'保洁清洗'),
        (1,'家电清洗'),
        (2,'上门维修'),
        (3,'搬货拉货'),
        (4,'空气净化'),
        (5,'简装刷新'),
        (6,'上门安装')
    }
    PAY_CHOICES ={
        (0,'一口价'),
        (1,'预定订金')
    }
    service_type=models.IntegerField(choices=SERVICE_TYPE_CHOICES,default=0,verbose_name='服务类型')
    pay_type=models.IntegerField(choices=PAY_CHOICES,default=0,verbose_name='付款方式')
    services_prices=models.JSONField(default=list,verbose_name='服务和价格')
    main_image=models.ImageField(upload_to="main_images/",null=True,blank=True,verbose_name='服务主图')
    detail_images=models.FileField(upload_to="detail_images/",null=True,blank=True,verbose_name='服务详情图')
    service_chra=models.CharField(max_length=10,verbose_name='服务特点')

    def add_service_price(self, name, unit_price, market_price):
        self.services_prices.append({
            'name': name,
            'unit_price': unit_price,
            'market_price': market_price
        })
        self.save()

    def remove_service_price(self, index):
        if 0 <= index < len(self.services_prices):
            del self.services_prices[index]
            self.save()

    def __str__(self):
        return self.service_type

